package yz.com.javautil.test;

import java.util.Scanner;

public class EscapeCsvString {
    private static final String CSV_DELIM = ",";
    private static final String CSV_QUOTE = "\"";
    private static final String CSV_CRLF = "\r\n";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("\nPlease input a string:");
            String input = scanner.nextLine();
            String output = escapeCsvString(input);
            System.out.printf("After escape: %s%n", output);
        }
    }

    private static String escapeCsvString(String fieldValue) {
        // 如果字段中包含逗号、双引号、换行符（规则6包含换行符（CRLF）、双引号和逗号的字段应该用双引号括起来）
        if (fieldValue.contains(CSV_DELIM) || fieldValue.contains(CSV_QUOTE) || fieldValue.contains(CSV_CRLF)) {
            // 替换单个双引号为两个双引号（规则7出现在字段内的双引号必须通过在其前面加上另一个双引号进行转义）
            fieldValue = "\"" + fieldValue.replace("\"", "\"\"") + "\"";
        }
        return fieldValue;
    }

}
